<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\model\Contacts;
use app\common\exception\UploadException;
use app\common\library\Sms as Smslib;
use app\common\library\Upload;
use think\Hook;

/**
 * Ajax异步请求接口
 * @internal
 */
class WebAjax extends WebIndexApi
{

    protected $noNeedLogin = ['sendsms'];
    protected $noNeedRight = [];
    protected $layout = '';
    /**
     * 上传文件
     */
    public function upload() {
        $attachment = null;
        //默认普通上传文件
        $file = $this->request->file('file');
        $name=input('name');
        try {
            $upload     = new Upload($file);
            $attachment = $upload->upload();
            $info = $attachment->toArray();
            $file = new \addons\qingdongams\model\File();
            $params = [
                'name'          =>  $name??$info['filename'],
                'save_name'     =>  $info['url'],
                'size'          =>  $info['filesize'],
                'types'         =>  $info['mimetype'],
                'file_path'     =>  $info['url'],
                'create_staff_id'     =>  empty($staff)?0:$staff->id,
            ];
            $file->data(array_filter($params));
            $file->save();
            $fileId = $file->id;

        } catch (UploadException $e) {
            return json_encode(['code' => 0, 'msg' => $e->getMessage()]);
        }
        $this->success(__('Uploaded successful'), [
            'id'  => $fileId,
            'url' => cdnurl($params['file_path'], true)
        ]);
    }

    /**
     * 发送验证码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $event 事件名称
     */
    public function sendSms()
    {
        $mobile = $this->request->post("mobile");
        $event = 'mobilelogin';

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        $last = Smslib::get($mobile, $event);
        if ($last && time() - $last['createtime'] < 60) {
//            $this->error(__('发送频繁'));
        }
        $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
        if ($ipSendTotal >= 5) {
//            $this->error(__('发送频繁'));
        }
        $customerId = Contacts::where(['mobile' => $mobile])->value('customer_id');
        if (!$customerId) {
            $this->error('手机号不存在');
        }
        if (!Hook::get('sms_send')) {
            $this->error(__('请在后台插件管理安装短信验证插件'));
        }
        $ret = Smslib::send($mobile, null, $event);
        if ($ret) {
            $this->success(__('发送成功'));
        } else {
            $this->error(__('发送失败，请检查短信配置是否正确'));
        }
    }
}
